<template>
  <div class="dashboard-container">
    <div class="dashboard-header">
      <h1>财务仪表盘</h1>
      <p>{{ currentDate }}</p>
    </div>
    
    <!-- 财务概览卡片 -->
    <div class="stats-cards">
      <div class="stat-card income">
        <div class="stat-icon">
          <span class="iconfont icon-plus-circle"></span>
        </div>
        <div class="stat-content">
          <div class="stat-label">总收入</div>
          <div class="stat-value income">{{ formatCurrency(financeStore.totalIncome) }}</div>
        </div>
      </div>
      
      <div class="stat-card expense">
        <div class="stat-icon">
          <span class="iconfont icon-minus-circle"></span>
        </div>
        <div class="stat-content">
          <div class="stat-label">总支出</div>
          <div class="stat-value expense">{{ formatCurrency(financeStore.totalExpense) }}</div>
        </div>
      </div>
      
      <div class="stat-card balance">
        <div class="stat-icon">
          <span class="iconfont icon-balance"></span>
        </div>
        <div class="stat-content">
          <div class="stat-label">当前余额</div>
          <div class="stat-value balance">{{ formatCurrency(financeStore.currentBalance) }}</div>
        </div>
      </div>
    </div>
    
    <!-- 收支趋势图表 -->
    <div class="charts-section">
      <div class="chart-card">
        <h3>收支趋势</h3>
        <div class="chart-container">
          <div class="chart-placeholder">收支趋势图表</div>
        </div>
      </div>
      
      <!-- 支出分类饼图 -->
      <div class="chart-card">
        <h3>支出分类占比</h3>
        <div class="chart-container">
          <div class="chart-placeholder">支出分类饼图</div>
        </div>
      </div>
    </div>
    
    <!-- 最近交易记录 -->
    <div class="recent-transactions">
      <div class="section-header">
        <h3>最近交易</h3>
        <router-link to="/transactions" class="view-all-link">查看全部</router-link>
      </div>
      
      <div class="transactions-list">
        <div v-if="financeStore.sortedTransactions.length === 0" class="empty-state">
          <p>暂无交易记录</p>
        </div>
        
        <div v-else class="transaction-item" v-for="transaction in recentTransactions" :key="transaction.id">
          <div class="transaction-icon">
            <span class="icon" :class="transaction.type === 'income' ? 'income' : 'expense'">
              {{ transaction.type === 'income' ? '+' : '-' }}
            </span>
          </div>
          
          <div class="transaction-info">
            <div class="transaction-category">{{ getCategoryName(transaction.category) }}</div>
            <div class="transaction-meta">
              <span class="transaction-date">{{ formatDate(transaction.date) }}</span>
              <span v-if="transaction.description" class="transaction-desc">{{ transaction.description }}</span>
            </div>
          </div>
          
          <div class="transaction-amount" :class="transaction.type">
            {{ transaction.type === 'income' ? '+' : '-' }}{{ formatCurrency(transaction.amount) }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useFinanceStore } from '../store/finance';

const financeStore = useFinanceStore();

// 获取当前日期
const currentDate = computed(() => {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
  const weekday = weekdays[date.getDay()];
  return `${year}年${month}月${day}日 ${weekday}`;
});

// 获取最近的5条交易记录
const recentTransactions = computed(() => {
  return financeStore.sortedTransactions.slice(0, 5);
});

// 获取分类名称
const getCategoryName = (categoryId: string): string => {
  const category = financeStore.categories.find(cat => cat.id === categoryId);
  return category ? category.name : '未知分类';
};

// 格式化货币
const formatCurrency = (amount: number): string => {
  return '¥' + amount.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  });
};

// 格式化日期
const formatDate = (dateString: string): string => {
  const date = new Date(dateString);
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${month}-${day}`;
};

// 准备图表数据
const chartData = computed(() => {
  const monthlyStats = financeStore.monthlyStats;
  const months = Object.keys(monthlyStats).sort();
  
  return {
    columns: ['月份', '收入', '支出'],
    rows: months.map(month => ({
      '月份': month,
      '收入': monthlyStats[month].income,
      '支出': monthlyStats[month].expense
    }))
  };
});

// 图表配置
const chartOptions = {
  legend: {
    position: 'top'
  },
  xAxis: {
    label: {
      autoHide: true
    }
  },
  yAxis: {
    label: {
      formatter: (v: number) => '¥' + v
    }
  },
  tooltip: {
    formatter: (datum: any) => {
      return {
        name: datum.name,
        value: '¥' + datum.value.toLocaleString('zh-CN')
      };
    }
  }
};

// 饼图数据
const pieData = computed(() => {
  const categoryStats = financeStore.categoryStats;
  const expenseTransactions = financeStore.transactions.filter(t => t.type === 'expense');
  const expenseByCategory: Record<string, number> = {};
  
  expenseTransactions.forEach(t => {
    if (!expenseByCategory[t.category]) {
      expenseByCategory[t.category] = 0;
    }
    expenseByCategory[t.category] += t.amount;
  });
  
  return {
    columns: ['分类', '金额'],
    rows: Object.entries(expenseByCategory).map(([categoryId, amount]) => ({
      '分类': getCategoryName(categoryId),
      '金额': amount
    }))
  };
});

// 饼图配置
const pieOptions = {
  legend: {
    position: 'right'
  },
  tooltip: {
    formatter: (datum: any) => {
      const total = datum.points.reduce((sum: number, point: any) => sum + point.value, 0);
      const percentage = ((datum.value / total) * 100).toFixed(1);
      return {
        name: datum.name,
        value: `¥${datum.value.toLocaleString('zh-CN')} (${percentage}%)`
      };
    }
  }
};

// 组件挂载时初始化数据
onMounted(() => {
  financeStore.loadFromLocalStorage();
  if (financeStore.transactions.length === 0) {
    financeStore.initMockData();
  }
});
</script>

<style scoped>
.dashboard-container {
  padding: 24px;
}

.dashboard-header {
  margin-bottom: 24px;
}

.dashboard-header h1 {
  font-size: 24px;
  margin: 0 0 8px 0;
}

.dashboard-header p {
  color: var(--color-text-secondary);
  margin: 0;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 16px;
  background-color: var(--color-bg-2);
  border-radius: 8px;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-2);
}

.stat-icon {
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  margin-right: 16px;
}

.stat-icon.income {
  background-color: var(--color-success-light-1);
}

.stat-icon.expense {
  background-color: var(--color-danger-light-1);
}

.stat-icon.balance {
  background-color: var(--color-info-light-1);
}

.stat-icon .icon {
  font-size: 24px;
}

.stat-icon.income .icon {
  color: var(--color-success);
}

.stat-icon.expense .icon {
  color: var(--color-danger);
}

.stat-icon.balance .icon {
  color: var(--color-info);
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: var(--color-text-secondary);
  margin-bottom: 4px;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
}

.stat-value.income {
  color: var(--color-success);
}

.stat-value.expense {
  color: var(--color-danger);
}

.stat-value.balance {
  color: var(--color-info);
}

.charts-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 24px;
  margin-bottom: 24px;
}

.chart-card {
  background-color: var(--color-bg-2);
  border-radius: 8px;
  padding: 20px;
}

.chart-card h3 {
  font-size: 18px;
  margin: 0 0 16px 0;
}

.chart-container {
  height: 300px;
}

.recent-transactions {
  background-color: var(--color-bg-2);
  border-radius: 8px;
  padding: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-header h3 {
  font-size: 18px;
  margin: 0;
}

.view-all-link {
  color: var(--color-primary);
  text-decoration: none;
  font-size: 14px;
}

.view-all-link:hover {
  text-decoration: underline;
}

.transactions-list {
  max-height: 400px;
  overflow-y: auto;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: var(--color-text-secondary);
}

.transaction-item {
  display: flex;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid var(--color-border);
}

.transaction-item:last-child {
  border-bottom: none;
}

.transaction-icon {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  margin-right: 16px;
}

.transaction-icon .icon {
  font-size: 16px;
  font-weight: bold;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
}

.transaction-icon .icon.income {
  background-color: var(--color-success-light-1);
  color: var(--color-success);
}

.transaction-icon .icon.expense {
  background-color: var(--color-danger-light-1);
  color: var(--color-danger);
}

.transaction-info {
  flex: 1;
}

.transaction-category {
  font-size: 16px;
  margin-bottom: 4px;
}

.transaction-meta {
  font-size: 14px;
  color: var(--color-text-secondary);
}

.transaction-date {
  margin-right: 12px;
}

.transaction-amount {
  font-size: 16px;
  font-weight: 600;
}

.transaction-amount.income {
  color: var(--color-success);
}

.transaction-amount.expense {
  color: var(--color-danger);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .charts-section {
    grid-template-columns: 1fr;
  }
  
  .chart-container {
    height: 250px;
  }
}
</style>